package net.wicp.tams.duckula.plugin;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import net.wicp.tams.common.Plugin;
import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.duckula.plugin.bean.DuckulaPackage;

public abstract class Utils {

	public static Plugin newPlugin(String pluginDir, String className, ClassLoader parent, String... excludes) {
		Plugin tempObj = new Plugin(pluginDir, className, parent, null, Arrays.asList(excludes));
		tempObj.getLoad().addToClassLoader(IOUtil.mergeFolderAndFilePath(pluginDir, "/lib"));
		return tempObj;
	}

	// "net.wicp.tams.duckula.plugin.IReceive","net.wicp.tams.duckula.plugin.ReceiveAbs"
	public static IReceive loadReceive(Plugin plugin, JSONObject params) {
		IReceive retobj = (IReceive) plugin.newObject(params);
		return retobj;
	}

	// "net.wicp.tams.duckula.plugin.ISerialize"
	public static ISerialize loadSerialize(Plugin plugin) {
		return (ISerialize) plugin.newObject();
	}

	/***
	 * 得到有效的数据
	 * 
	 * @param duckulaPackage
	 * @param rowNo
	 * @return
	 */
	public static Map<String, String> getUseData(DuckulaPackage duckulaPackage, int rowNo) {
		Map<String, String> map = new HashMap<>();
		String[] data = null;
		switch (duckulaPackage.getEventTable().getOptType()) {
		case insert:
		case update:
			data = duckulaPackage.getAfters()[rowNo];
			break;
		case delete:
			data = duckulaPackage.getBefores()[rowNo];
			break;
		default:
			break;
		}
		if (data == null) {
			return map;
		} else {
			for (int i = 0; i < duckulaPackage.getEventTable().getColsNum(); i++) {
				map.put(duckulaPackage.getEventTable().getCols()[i], data[i]);
			}
		}
		return map;
	}

	public static final String colBefore = "before";
	public static final String colAfter = "after";

	public static Map<String, Map<String, String>> getAllData(DuckulaPackage duckulaPackage, int rowNo) {
		Map<String, Map<String, String>> returnobj = new HashMap<>();

		String[] dataBefore = null;
		String[] dataAfter = null;
		switch (duckulaPackage.getEventTable().getOptType()) {
		case insert:
			dataAfter = duckulaPackage.getAfters()[rowNo];
			break;
		case update:
			dataBefore = duckulaPackage.getBefores()[rowNo];
			dataAfter = duckulaPackage.getAfters()[rowNo];
			break;
		case delete:
			dataBefore = duckulaPackage.getBefores()[rowNo];
			break;
		default:
			break;
		}
		if (dataBefore != null) {
			Map<String, String> tempMap = new HashMap<>();
			for (int i = 0; i < duckulaPackage.getEventTable().getColsNum(); i++) {
				tempMap.put(duckulaPackage.getEventTable().getCols()[i], dataBefore[i]);
			}
			returnobj.put(colBefore, tempMap);
		}
		if (dataAfter != null) {
			Map<String, String> tempMap = new HashMap<>();
			for (int i = 0; i < duckulaPackage.getEventTable().getColsNum(); i++) {
				tempMap.put(duckulaPackage.getEventTable().getCols()[i], dataAfter[i]);
			}
			returnobj.put(colAfter, tempMap);
		}
		return returnobj;
	}
}
